package com.xinlang.excel;

import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.xinlang.excel.io.ExcelTableWriter;
import com.xinlang.excel.io.TableWriter;
import com.xinlang.excel.io.TextTableWriter;

/**
 * ����Table�Ĺ���
 * 
 */
public class TableUtil {
	// TODO: ��һ��

	// ����ͳ�Ʊ���ģ�fieldName��ԭ����newFieldName�ǰٷֱȵ�����
	static public void appendPercentage(Table table, String fieldName, String newFieldName) {
		Double total = 0.0;
		for (String key : table.getRowKeys()) {
			Object value = table.get(key, fieldName);
			if (value instanceof Double) {
				total += (Double) value;
			} else if (value instanceof Integer) {
				total += (Integer) value;
			} else if (value instanceof Long) {
				total += (Long) value;
			}
		}
		// to make sure total is not ZERO
		if (Math.abs(total) > 1e-9) {
			for (String key : table.getRowKeys()) {
				Object value = table.get(key, fieldName);
				Double percent = 0.0;
				if (value instanceof Double) {
					percent = (Double) value / total;
				} else if (value instanceof Integer) {
					percent = (Integer) value / total;
				} else if (value instanceof Long) {
					percent = (Long) value / total;
				}
				table.put(key, newFieldName, percent);
			}
		}
	}

	// ��һ��Table����ת��List<Table>�б�
	static public List<Table> toList(Table table) {
		List<Table> tables = new ArrayList<Table>();
		tables.add(table);
		return tables;
	}

	// ���List<Table>
	static public final void dumpTables(List<Table> tables, PrintStream out) {
		try {
			TextTableWriter writer = new TextTableWriter(out);
			for (Table table : tables) {
				writer.write(table);
			}
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static public final void dumpTables(List<Table> tables) {
		dumpTables(tables, System.out);
	}

	static public final void dumpTable(Table table) {
		dumpTables(toList(table));
	}

	// ���List<Table>
	static public final void dumpToExcel(List<Table> tables, String outputFile) throws IOException {
		TableWriter writer = new ExcelTableWriter(outputFile);
		for (Table table : tables) {
			writer.write(table);
		}
		writer.close();
	}

	// ����Table��һ�е������
	static public int getSum(Map<String, Object> row) {
		int total = 0;

		for (Map.Entry<String, Object> entry : row.entrySet()) {
			Object value = entry.getValue();
			if (value != null) {
				if (value instanceof Integer) {
					total += (Integer) value;
				} else if (value instanceof Long) {
					total += ((Long) value).intValue();
				}
			}
		}
		return total;
	}

}
